package com.laikan.reader.core.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 创建文件的工具类
 *
 * @author wangxiaole
 */
@SuppressLint ("SimpleDateFormat")
public class FileUtil {

    public static final String APP_NAME = "LaikanReader";
    public static final String TYPE_JPG = ".png";
    public static final String CROP_LOGO = "/crop_logo.png";
    public static String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final String IMAGE_SD_CACHE_PATH = SD_PATH + "/" + APP_NAME + "/images_cache/";
    public static final String ROOT_SD_PATH = SD_PATH + "/" + APP_NAME + "/";
    public static final String JSON_PATH = SD_PATH + "/" + APP_NAME + "/data/";
    public static String DATA_PATH = Environment.getDownloadCacheDirectory().getAbsolutePath();
    public static final String IMAGE_DATA_CACHE_PATH = DATA_PATH + "/" + APP_NAME + "/image_cache/";
    public static final String DOWNLOAD_SD_PATH = SD_PATH + "/" + APP_NAME + "/download/";
    public static final String DOWNLOAD_DATA_PATH = DATA_PATH + "/" + APP_NAME + "/download/";
    public static final String ROOT_DATA_PATH = DATA_PATH + "/" + APP_NAME + "/";
    public static File CamerPhotoFile;
    public static File updateDir = null;
    public static File updateFile = null;

    /**
     * 写加密文件
     *
     * @param pathName 文件路径 + JSON内容
     * @param content
     */
    public static void writeFileDes(String pathName, String content) {

        File file = new File(pathName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            DesUtils des = new DesUtils("LaikanReader");
            fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(des.encrypt(content));
            bw.close();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos != null) {
                try {
                    fos.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取加密文件内容
     *
     * @param pathName 文件路径
     *
     * @return
     */
    public static String readFileStringDes(String pathName) {
        File file = new File(pathName);
        FileInputStream fis = null;
        BufferedReader reader = null;
        String string = null;
        DesUtils des = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                    builder.append(s);
                }
                des = new DesUtils("LaikanReader");
                string = des.decrypt(builder.toString());
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return string;
    }

    public static byte[] readInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        inputStream.close();
        return outstream.toByteArray();
    }

    /**
     * 递归删除文件夹
     *
     * @param f
     */
    public static void delFile(File f) {
        if (f.isDirectory()) {
            File[] list = f.listFiles();
            for (int i = 0; i < list.length; i++) {
                if (list[i].isDirectory()) {
                    delFile(list[i]);
                }else {
                    if (list[i].isFile()) {
                        list[i].delete();
                    }
                }
            }
            f.delete();
        }else {
            if (f.isFile()) {
                f.delete();
            }
        }
    }

    public static File createCameraPhoto() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        CamerPhotoFile = new File(IMAGE_SD_CACHE_PATH);
        if (!CamerPhotoFile.exists()) {
            CamerPhotoFile.mkdirs();
        }
        CamerPhotoFile = new File(CamerPhotoFile, "IMG" + dateFormat.format(date) + TYPE_JPG);

        return CamerPhotoFile;
    }

    public static File getFileFromPath(String filePath, String fileName) {
        File dir = new File(filePath);
        if (!dir.isDirectory()) {
            dir.delete();
            dir.mkdirs();
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return new File(filePath + fileName);
    }

    public static void saveMyBitmap(Bitmap mBitmap, String type) {
        File f ;
        if("isPosterImg".equals(type)){
            f = getFileFromPath(PublicUtil.getRootPath() + BookFileUtils.POSTERIMGFILEPATH , "/lk_poster_bg.png");
        }else{
            f = getFileFromPath(PublicUtil.getRootPath() + BookFileUtils.SPLASHIMGFILEPATH, "/lk_splash_bg.png");
        }
        try {
            f.createNewFile();
            FileOutputStream fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param url 要下载的文件URL
     */
    public static void downloadSplashImg(Context context, String url, final String type) {

        new FrescoManager.LoadImageFrescoBuilder(context, new SimpleDraweeView(context), url)
            .setBitmapDataSubscriber(new BaseBitmapDataSubscriber() {
                @Override
                protected void onNewResultImpl(Bitmap bitmap) {
                    if (bitmap != null) {

                        saveMyBitmap(bitmap,type);
                    }
                }

                @Override
                protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

                }
            }).build();
    }

    /***
     * 创建文件
     */
    public static void createApkFile(String name) {
        if (isHaveSDCard()) {
            updateDir = new File(DOWNLOAD_SD_PATH);
            updateFile = new File(DOWNLOAD_SD_PATH + name + ".apk");
        }else {
            updateDir = new File(DOWNLOAD_DATA_PATH);
            updateFile = new File(DOWNLOAD_DATA_PATH + name + ".apk");
        }

        if (!updateDir.exists()) {
            updateDir.mkdirs();
        }
        if (!updateFile.exists()) {
            try {
                updateFile.createNewFile();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建文件
     */
    public static void createImgFile(String name) {
        if (isHaveSDCard()) {

            File image = new File(IMAGE_SD_CACHE_PATH);
            if (!image.exists()) {
                image.mkdirs();
            }
            File download = new File(DOWNLOAD_SD_PATH);
            if (!download.exists()) {
                download.mkdirs();
            }
        }else {

            File image = new File(IMAGE_DATA_CACHE_PATH);
            if (!image.exists()) {
                image.mkdirs();
            }
            File download = new File(DOWNLOAD_DATA_PATH);
            if (!download.exists()) {
                download.mkdirs();
            }

        }
    }

    /**
     * 复制文件
     *
     * @param is
     * @param os
     */
    public static void CopyStream(InputStream is, OutputStream os) {
        final int buffer_size = 1024;
        try {
            byte[] bytes = new byte[buffer_size];
            for (; ; ) {
                int count = is.read(bytes, 0, buffer_size);
                if (count == -1) {
                    break;
                }
                os.write(bytes, 0, count);
            }
        }catch (Exception ex) {
        }
    }

    /**
     * 写文件
     *
     * @param pathName 文件路径 + JSON内容
     * @param content
     */
    public static void writeFile(String pathName, String content) {
        File file = new File(pathName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(content);
            bw.close();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos != null) {
                try {
                    fos.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取文件
     *
     * @param pathName 文件路径+名字
     *
     * @return
     */
    public static InputStream readFile(String pathName) {
        File file = new File(pathName);
        FileInputStream fis = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return fis;
    }

    /**
     * 读取文件内容
     *
     * @param pathName 文件路径
     *
     * @return
     */
    public static String readFileString(String pathName) {
        File file = new File(pathName);
        FileInputStream fis = null;
        BufferedReader reader = null;
        String string = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                    builder.append(s);
                }
                string = builder.toString();
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return string;
    }

    /**
     * 保存图片
     *
     * @param path
     * @param name
     * @param bitmap
     */
    @SuppressLint ("DefaultLocale")
    public static void writeBitmap(String path, String name, Bitmap bitmap) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        File _file = new File(path + name);
        if (_file.exists()) {
            _file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(_file);
            if (name != null && !"".equals(name)) {
                int index = name.lastIndexOf(".");
                if (index != -1 && (index + 1) < name.length()) {
                    String extension = name.substring(index + 1).toLowerCase();
                    if ("png".equals(extension)) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    }else if ("jpg".equals(extension) || "jpeg".equals(extension)) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
                    }
                }
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (fos != null) {
                try {
                    fos.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取图片
     *
     * @param pathName
     *
     * @return
     */
    public static Bitmap readBitmap(String pathName) {
        InputStream in = readFile(pathName);
        if (in != null) {
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            try {
                in.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        return null;
    }

    /**
     * 获取文件名
     *
     * @param filePathName
     *
     * @return
     */
    public static String getFileName(String filePathName) {
        if (filePathName != null && !"".equals(filePathName)) {
            int index = filePathName.lastIndexOf('/');
            if (index != -1 && (index + 1) < filePathName.length()) {
                return filePathName.substring(index + 1);
            }
        }
        return "";
    }

    /**
     * 修改文件名
     *
     * @param fileName
     *
     * @return
     */
    public static String modifyFileName(String fileName) {
        if (fileName == null) {
            return null;
        }
        String s = "\\/:*?\"<>|";
        StringBuffer sb = new StringBuffer();
        char[] chars = fileName.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (s.indexOf(chars[i]) == -1) {
                sb.append(chars[i]);
            }
        }
        return sb.toString();
    }

    /**
     * 计算文件夹大小
     *
     * @param f
     *
     * @return
     */
    public static long getFileLength(File f) {
        long length = 0;
        if (f != null && f.isDirectory()) {
            File[] list = f.listFiles();
            for (int i = 0; i < list.length; i++) {
                if (list[i].isFile()) {
                    length += list[i].length();
                }
            }
        }
        return length;
    }

    /**
     * 删除文件
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file != null && file.exists() && file.isFile()) {
            file.delete();
        }
    }

    /**
     * 判断是否存在SD卡
     *
     * @return true，有SD卡。false，无SD卡
     */
    public static boolean isHaveSDCard() {
        String SDState = Environment.getExternalStorageState();
        return SDState.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 判断SD卡空间是否满
     *
     * @return
     */
    public static boolean storageIsFull() {
        StatFs fs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
        return !(fs.getAvailableBlocks() > 1);
    }

    /**
     * 递归删除文件及目录
     * @param path
     */
    public static void deleteDir(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File subFile : files) {
                        if (subFile.isDirectory()) { deleteDir(subFile.getPath()); }else { subFile.delete(); }
                    }
                }
                file.delete();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
